package com.ruoyi.crop.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.crop.api.domain.City;
import com.ruoyi.crop.api.domain.Farmer;
import com.ruoyi.crop.service.CityService;
import com.ruoyi.crop.service.FarmerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/farmer")
public class HouseController extends BaseController {
    @Autowired
    FarmerService farmerService;
    @Autowired
    CityService cityService;

    /**
     * 获取农户管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Farmer farmer)
    {
        startPage();
        List<Farmer> list = farmerService.selectFarmerList(farmer);
        return getDataTable(list);
    }

    /**
     * 根据农户编号获取详细信息
     */
    @GetMapping(value = "/{farmerId}")
    public AjaxResult getInfo(@PathVariable Integer farmerId)
    {
        return success(farmerService.getById(farmerId));
    }

    /**
     * 新增农户管理
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Farmer farmer)
    {
        if (!farmerService.checkFarmerNameUnique(farmer)){
            return error("新增农户"+farmer.getFarmerName()+"失败,农户已存在");
        }
        farmer.setCreateBy(SecurityUtils.getUsername());
        farmer.setCreateTime(new Date());
        return toAjax(farmerService.save(farmer));
    }

    /**
     * 修改农户管理
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Farmer farmer)
    {
        if (!farmerService.checkFarmerNameUnique(farmer)){
            return error("修改农户"+farmer.getFarmerName()+"失败,农户已存在");
        }
        farmer.setUpdateBy(SecurityUtils.getUsername());
        farmer.setUpdateTime(new Date());
        return toAjax(farmerService.updateById(farmer));
    }

    /**
     * 删除农户管理
     */
    @DeleteMapping("/{farmerIds}")
    public AjaxResult remove(@PathVariable Integer[] farmerIds)
    {
        return toAjax(farmerService.removeBatchByIds(Arrays.asList(farmerIds)));
    }

//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Farmer farmer)
//    {
//        List<Farmer> farmerList = farmerService.selectFarmerList(farmer);
//        ExcelUtils.exportExcel(farmerList,"farmer","sheet1",response);
//    }



}
